#!/usr/bin/python

from google.appengine.api import users
from google.appengine.ext.webapp import template

import copy
import json
import logging
import os
import random
import webapp2

import gamedb
import settings

LOG = logging.getLogger(__name__)


class MainHandler(webapp2.RequestHandler):
  def get(self):
    user = users.get_current_user()

    # Get the configs of all games.
    games = {}
    for game, game_module in settings.GAMES.iteritems():
      games[game] = game_module.CONFIG

    template_values = {
        'games': json.dumps(games),
        'jquery_url': settings.JQUERY_URL,
        'nickname': user.nickname(),
        'email': user.email(),
        }
    self.response.content_type = 'text/html'
    self.response.headers.add('Cache-Control', 'no-cache')
    self.response.out.write(template.render('tpl/main.html', template_values))


class CreateHandler(webapp2.RequestHandler):
  def post(self):
    # Validate the game parameter.
    game = self.request.get('game')
    if game not in settings.GAMES:
      LOG.warning('invalid game %s', game)
      webapp2.abort(403)
    config = settings.GAMES[game].CONFIG

    # Sanity check for num_players
    num_players = self.request.get('num_players')
    if not num_players.isdigit():
      LOG.warning('invalid num_players %s', num_players)
      webapp2.abort(403)
    num_players = int(num_players)
    if (num_players < config['min_players'] or
        num_players > config['max_players']):
      LOG.warning('invlaid num_players %s for game %s', num_players, game)
      webapp2.abort(403)

    players = [''] * num_players
    owner = players[0] = users.get_current_user().email()

    # Sanity check for players
    for i in xrange(1, num_players):
      type = self.request.get('player%d_type' % i)
      if type == 'ai':
        if not config['has_ai']:
          LOG.warning('game %s does not support AI', game)
          webapp2.abort(403)
        players[i] = type
      elif type == 'public':
        players[i] = type
      elif type == 'email':
        email = self.request.get('player%d_email' % i)
        if '@' not in email:
          LOG.warning('invalid player email %s', email)
          webapp2.abort(403)
        players[i] = email.strip()
      else:
        LOG.warning('invalid player type %s', type)
        webapp2.abort(403)

    # Check for duplicated players
    tmp_players = copy.copy(players)
    tmp_players.sort()
    for i in xrange(len(tmp_players) - 1):
      p = tmp_players[i]
      if p != 'ai' and p != 'public' and p == tmp_players[i + 1]:
        LOG.warning('duplicated player %s', p)
        webapp2.abort(403)

    if self.request.get('random') == 'on':
      random.shuffle(players)

    # Create the game.
    game_id = gamedb.CreateGameEntity(
      game, self.request.get('name'), players,
      self.request.get('public') == 'on', owner)
    return self.redirect('/game/%d/' % game_id)


class GameHandler(webapp2.RequestHandler):
  def get(self, game_id, action):
    if not game_id.isdigit():
      LOG.warning('invalid game id %s', game_id)
      webapp2.abort(403)

    game_id = int(game_id)

    game_entity = gamedb.GetGameEntity(game_id)
    if not game_entity:
      LOG.warning('cannot find game %s', game_id)
      webapp2.abort(404)

    game_module = settings.GAMES[game_entity.game]
    game_module.Game(game_entity, self.request, self.response).Process(action)


# URL mapping:
#   /                  main page
#   /create            game creation handler
#   /game/[0-9]+/(.*)  game page

app = webapp2.WSGIApplication([
    (r'/', MainHandler),
    (r'/create', CreateHandler),
    (r'/game/([0-9]+)/(.*)', GameHandler),
    ], debug=settings.DEBUG)
